package com.admin.interfaces.web;

import com.foxinmy.weixin4j.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author jy.hu , 2013-1-29
 * @title Action基础类
 * @description 提供对request等对象的常用操作方法
 */
public class BaseController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ServletContext servletContext;

    protected HttpServletRequest getRequest() {
        return request;
    }

    // 获取ServletContext
    protected ServletContext getServletContext() {
        return servletContext;
    }

    // 获取Attribute
    protected Object getAttribute(String name) {
        return getRequest().getAttribute(name);
    }

    // 设置Attribute
    protected void setAttribute(String name, Object value) {
        getRequest().setAttribute(name, value);
    }

    // 获取Parameter
    protected String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    // 获取Parameter数组
    protected String[] getParameterValues(String name) {
        return getRequest().getParameterValues(name);
    }

    // 获取Session
    protected HttpSession getSession() {
        return getSession(true);
    }

    protected HttpSession getSession(boolean isNew) {
        return getRequest().getSession(isNew);
    }

    // 获取Session属性的值
    protected Object getSession(String name) {
        HttpSession session = getSession();
        return session.getAttribute(name);
    }

    // 设置Session属性的值
    protected void setSession(String name, Object value) {
        HttpSession session = getSession();
        session.setAttribute(name, value);
    }

    // 移除Session属性的值
    protected void removeSession(String name) {
        HttpSession session = getSession();
        session.removeAttribute(name);
    }

    // 获取Cookie
    protected String getCookie(String name) {
        Cookie cookies[] = getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    // 获取Cookie
    protected String removeCookie(String name, HttpServletResponse response) {
        Cookie cookies[] = getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return null;
    }

    protected String getRootLocation() {
        int port = request.getServerPort();
        if (port == 80) {
            return String.format("%s://%s", request.getScheme(),
                    request.getServerName());
        } else {
            return String.format("%s://%s:%s", request.getScheme(),
                    request.getServerName(), port);
        }
    }

    protected String getFullLoction() {
        String root = getRootLocation();
        String queryString = request.getQueryString();
        return String.format("%s%s%s", root, request.getRequestURI(),
                StringUtil.isNotBlank(queryString) ? "?" + queryString : "");
    }

    protected String getIpAddr() {
        HttpServletRequest request = getRequest();
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0
                || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")
                    || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
